package com.mobipe.sutto.grizzly;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

import org.glassfish.grizzly.filterchain.FilterChainBuilder;
import org.glassfish.grizzly.filterchain.TransportFilter;
import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder;
import org.glassfish.grizzly.strategies.SameThreadIOStrategy;
import org.glassfish.grizzly.threadpool.GrizzlyExecutorService;
import org.glassfish.grizzly.threadpool.ThreadPoolConfig;

import com.mobipe.sutto.core.AbstractServer;

/**
 * @author kohachiro
 *
 */
public class Server extends AbstractServer {
	final TCPNIOTransport transport;
	static Server instance;
	/**
	 * 
	 */
	public Server() {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) threadPool;
        ThreadPoolConfig config = ThreadPoolConfig.defaultConfig().copy()
                .setCorePoolSize(threadPoolExecutor.getCorePoolSize())
                .setMaxPoolSize(threadPoolExecutor.getMaximumPoolSize())
                .setPoolName("GRIZZLY-SERVER");
        ExecutorService executorService =
                GrizzlyExecutorService.createInstance(config);
        
        FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless();
        filterChainBuilder.add(new TransportFilter());
        filterChainBuilder.add(new ServerHandler());
        TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance();
        builder.setIOStrategy(SameThreadIOStrategy.getInstance());
        builder.setTcpNoDelay(true);
        //builder.setReuseAddress(true);
        transport = builder.build();
        transport.setProcessor(filterChainBuilder.build());
	}

	public static void main(String[] args) throws Exception {
		instance = new Server();
		instance.start();
		instance.bind();
	}

	@Override
	public void bind() throws Exception {
		System.out.println("Listening on port " + PORT);		
		instance.transport.bind(PORT);
		instance.transport.start();
		System.in.read();
	}

	@Override
	public void start() {
		// TODO Auto-generated method stub
		
	}
}
